package com.efounder.zone.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.ShareToZoneRefreshEvent;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.model.TabMenuClickEvent;
import com.efounder.chat.model.UserEvent;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.zone.R;
import com.efounder.zone.activity.SendPostActivity;
import com.efounder.zone.activity.ZoneBlackListActivity;
import com.efounder.zone.adapter.MainZoneAdapter;
import com.efounder.zone.bean.TalksBean;
import com.efounder.zone.bean.ZoneAddPopWindowBean;
import com.efounder.zone.event.MobileZoneDetailBackEvent;
import com.efounder.zone.event.MobileZoneEvent;
import com.efounder.zone.event.MobileZoneFilterEvent;
import com.efounder.zone.event.MobileZoneRefreshEvent;
import com.efounder.zone.event.MobileZoneTransmitContentEvent;
import com.efounder.zone.util.ZoneRequestUtil;
import com.efounder.zone.widget.CommonZonePopWindow;
import com.efounder.zone.widget.MutiContentDisplayView;
import com.efounder.zone.widget.StatusAlert;
import com.efounder.zone.widget.ThumbsCommentsTransmitView;
import com.efounder.zone.widget.ZoneRedactPopupWindow;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.utilcode.util.ActivityUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import static com.efounder.chat.fragment.ChatSenderFragment.chatpath;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.pansoft.chat.photo.JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE;
import static com.efounder.zone.adapter.MainZoneAdapter.JUMP_DETAIL;

/**
 * @author will
 * 空间状态主页面
 */
public class MainZoneFragment extends BaseFragment {

    private static final String TAG = "MainZoneFragment";
    public static final int REQUEST_SEND_POST = 21114;
    private RecyclerView recyclerView;
    protected TextView tvTitle;
    private MainZoneAdapter adapter;
    protected SmartRefreshLayout refreshLayout;
    //    private RelativeLayout rlTitle;//标题栏
    private String lastTalksTime = String.valueOf(System.currentTimeMillis());//用于加载更多，传入的时间
    private ImageView ivAdd;
    private Button butAddfriend;
    protected CommonZonePopWindow commonOtherPopWindow;
    private List<TalksBean> items = new ArrayList<>();//动态数据列表
    protected boolean isRefresh = true;//是否是下拉刷新，第一次加载也算
    protected boolean isSelf = true;//是否是自己的空间
    //如果isSelf=false,是看别人的空间,则为传过来的id，否则是自己的空间，取EV里的
    private int userId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));


    //默认数据源（加载全部人的）
    protected String dataOrigin = "getEventListFilterBlackList";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.mobile_zone_activity_main_zone, container, false);
        if (getUserVisibleHint()) {
            LoadingDataUtilBlack.show(getActivity(), ResStringUtil.getString(R.string.common_text_please_wait));
        }
        if (getArguments() != null && getArguments().containsKey("other_user_id")) {
            isSelf = false;
            //如果isSelf=false,是看别人的空间,则为传过来的id
            userId = getArguments().getInt("other_user_id", -1);
        }

        User user = WeChatDBManager.getInstance().getOneUserById(userId, UserEvent.EVENT_ZONE);
        //头部数据占位
        TalksBean headerBean = new TalksBean();
        TalksBean.ObjBean objBean = new TalksBean.ObjBean();
        //用postContent保存背景图url
        objBean.setPostContent("");
        //背景图里的头像id
        objBean.setId(userId);
        //昵称
        objBean.setDevice(user.getNickName());
        //头像
        objBean.setPostCreatetime(user.getAvatar());
        headerBean.setObj(objBean);
        items.add(headerBean);
        initView(view);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        getBackgroundImage();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        MutiContentDisplayView.BitmapPool.release();
        EventBus.getDefault().unregister(this);
//        CommentUtil.cancelCommentInput();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        RefWatcher refWatcher = BaseApp.getRefWatcher(getActivity());
//        refWatcher.watch(this);
    }
//    @Override
//    protected void onStop() {
//        super.onStop();
//        EFHttpRequest.cancelRequest(TAG);
//    }

    @Override
    public void onResume() {
        super.onResume();
        refreshUser();
        adapter.notifyDataSetChanged();

        User user = WeChatDBManager.getInstance().getOneFriendById(userId);
        if (user.isExist() || userId == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
            butAddfriend.setVisibility(View.GONE);

        } else {
            butAddfriend.setVisibility(View.VISIBLE);
            butAddfriend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("id", userId);
                    ChatActivitySkipUtil.startUserInfoActivity(getActivity(), intent);
                }
            });
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        refreshUser();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK && requestCode == AddZonePopWindow.REQUEST_CODE_SELECT_VIDEO) {
//            //录制视频完成
//            String video_path = data.getStringExtra("path");
//            String videoTime = data.getStringExtra("videoTime");
//            double fileSize = FileSizeUtil.getFileOrFilesSize(video_path, FileSizeUtil.SIZETYPE_KB);
//            if (fileSize < 20) {
//                //视频过小，录制失败，不发送消息
//                ToastUtil.showToast(getActivity(), R.string.zone_video_record_fail);
//                return;
//            }
////            LogUtils.aTag(TAG, video_path);
//            LoadingDataUtilBlack.show(getActivity(), ResStringUtil.getString(R.string.common_text_please_wait));
//            PansoftCloudUtil.getCloudRes(video_path, new PansoftCloudUtil.UpLoadListener() {
//                @Override
//                public void getHttpUrl(Boolean isSuccess, String url) {
//                    if (isSuccess) {
////                        LogUtils.aTag(TAG, url);
//                        LoadingDataUtilBlack.dismiss();
//                        String content = new CreateBeanUtil().createVideoContent("", url);
//                        TalksBean talksBean = new CreateBeanUtil().createTalksBean(2, DeviceUtils.getModel(), content);
//                        sendPost(talksBean);
//                    } else {
//                        LoadingDataUtilBlack.dismiss();
//                        StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
//                                .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_publish_fail));
//                    }
//                }
//            });
//            return;
//        }
        if (resultCode == RESULT_OK && requestCode == REQUEST_SEND_POST) {
            if (data.getExtras() == null) {
                StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_publish_fail));
            } else {
                TalksBean talksBean = (TalksBean) data.getExtras().get("talksBean");
                StatusAlert.successAlert(getActivity(), LayoutInflater.from(getActivity())
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_publish_success));
                if (items.size() >= 2 && items.get(1) != null && items.get(1).getObjType() == 0) {
                    //有消息提示
                    items.add(2, talksBean);
                    adapter.notifyItemInserted(2);
                    recyclerView.scrollToPosition(2);
                } else {
                    items.add(1, talksBean);
                    adapter.notifyItemInserted(1);
                    recyclerView.scrollToPosition(1);
                }
            }

        }
        if (resultCode == RESULT_OK && requestCode == JUMP_DETAIL) {
            int position = data.getIntExtra("position", -1);
            TalksBean talksBean = (TalksBean) data.getSerializableExtra("talksBean");
            items.remove(position);
            items.add(position, talksBean);
            adapter.notifyItemChanged(position);
        }
        /**
         * 更改背景图
         */
        if (requestCode == REQUEST_PIC_SELECTE_CODE && resultCode == RESULT_OK) {
            //图库选择照片
            LoadingDataUtilBlack.show(getContext(), ResStringUtil.getString(R.string.zone_update_background));
            List<String> images = ((ArrayList<String>) data.getExtras().get("mSelectedPics"));
            if (images != null && images.size() > 0) {
                String imgPath = images.get(0);
                //压缩
                if (!ImageUtil.isGifFile((new File(imgPath)))) {
                    ImageUtil.saveNewImage(imgPath, 1280, 1280);
                    imgPath = chatpath + ImageUtil.getFileName(imgPath) + ".pic";
                }
                PansoftCloudUtil.getCloudRes(imgPath, new PansoftCloudUtil.UpLoadListener() {
                    @Override
                    public void getHttpUrl(Boolean isSuccess, String url) {

                        if (isSuccess) {
                            Log.i("MyUserInfoActivity", R.string.zone_path_of_photo + url);
                            //返回成功，请求修改背景图
                            postBgImage(url);
                        } else {
                            //图片没有上传成功
                            LoadingDataUtilBlack.dismiss();
                            StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                                    .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_update_background_fail));
                        }
                    }
                });
            } else {
                LoadingDataUtilBlack.dismiss();
                StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_update_background_fail));
            }
        }
    }

    private void initView(View view) {
        recyclerView = view.findViewById(R.id.recyclerView);
        butAddfriend = (Button) view.findViewById(R.id.but_addfriend);

//        rlTitle = view.findViewById(R.id.title);
        adapter = new MainZoneAdapter(getActivity(), items, getFragmentManager());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
        adapter.setMoreClickListener(new MainZoneAdapter.onMoreClickListener() {
            @Override
            public void click(final int position, View v) {
                TalksBean talksBean = items.get(position);

                showItemPop(talksBean, position, v);

            }
        });
        adapter.setOnBgImageChangeListener(new MainZoneAdapter.OnBgImageChangeListener() {
            @Override
            public void onBgImageChange() {
                changeBgImage();
            }
        });
        // TODO: 18-6-29  
        adapter.setOnMessageClickedListener(new MainZoneAdapter.OnMessageClickedListener() {
            @Override
            public void onMessageClicked() {
                items.remove(1);
                adapter.notifyItemRemoved(1);
            }
        });
        refreshLayout = view.findViewById(R.id.refreshLayout);
        ClassicsHeader classicsHeader = view.findViewById(R.id.classic_header);
        classicsHeader.setSpinnerStyle(SpinnerStyle.Translate);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                getTalksData(lastTalksTime);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                getTalksData(String.valueOf(System.currentTimeMillis()));
            }
        });
        tvTitle = view.findViewById(R.id.tv_title);
        tvTitle.setText(R.string.zone_gravitational_all);
        ivAdd = view.findViewById(R.id.iv_add);
        ImageView ivback = view.findViewById(R.id.iv_back);
        ivback.setVisibility(View.INVISIBLE);
        //好友动态，则隐藏发说说按钮
        if (!isSelf) {
            ivAdd.setVisibility(View.INVISIBLE);
            ivback.setVisibility(View.VISIBLE);
            User user = WeChatDBManager.getInstance().getOneUserById(userId);
            tvTitle.setText(user.getNickName() + ResStringUtil.getString(R.string.zone_s_gravitational));
            if (user.getId() == Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                tvTitle.setText(R.string.zone_my_gravitational);
            }
        }
        initCommonPopView();
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commonOtherPopWindow.showPopupWindow(ivAdd);
            }
        });

        //内容跟随偏移
        refreshLayout.setEnableHeaderTranslationContent(true);
        //设置是否显示标题
        if (getArguments() != null && getArguments().containsKey("stubObject")) {
            StubObject stubObject = (StubObject) getArguments().getSerializable("stubObject");
            if (stubObject != null) {
                if (
                    //stubObject.getString("hideTitle", "").equals("1") ||
                        stubObject.getString("hideZoneTitle", "").equals("1")) {
                    view.findViewById(R.id.title).setVisibility(View.GONE);
                }
            }
        }
    }

    protected void initCommonPopView() {
        commonOtherPopWindow = CommonZonePopWindow.getInstance(getActivity());
        commonOtherPopWindow.setItemOnClickListener(new CommonZonePopWindow.PopWindowItemOnClickListener() {
            @Override
            public void onClick(View view, int position, ZoneAddPopWindowBean bean) {
                String currentTime = String.valueOf(System.currentTimeMillis());
                if (position == 0) {
                    Intent intent = new Intent(MainZoneFragment.this.getContext(), SendPostActivity.class);
                    startActivityForResult(intent, MainZoneFragment.REQUEST_SEND_POST);

                } else if (position == 1) {
                    isRefresh = true;
                    dataOrigin = "getEventListFilterBlackList";
                    refreshLayout.autoRefresh();
                    if (isSelf) {
                        tvTitle.setText(R.string.zone_gravitational_all);
                    }

                    // getTalksData(currentTime);
                } else if (position == 2) {
                    isRefresh = true;
                    dataOrigin = "friends";
                    refreshLayout.autoRefresh();
                    // getTalksData(currentTime);
                    if (isSelf) {
                        tvTitle.setText(R.string.zone_gravitational_friend);
                    }
                } else if (position == 3) {
                    isRefresh = true;
                    dataOrigin = "getEventListStar";
                    refreshLayout.autoRefresh();
                    if (isSelf) {
                        tvTitle.setText(R.string.zone_gravitational_follow);
                    }
                    //getTalksData(currentTime);
                } else if (position == 4) {
                    //黑名单
                    ZoneBlackListActivity.start(getActivity());
                }
            }
        });
    }

    private void showItemPop(final TalksBean talksBean, final int position, final View v) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        LoadingDataUtilBlack.show(getActivity());
        ZoneRequestUtil.getCommonRequest(TAG, "fans/getStarByUserid", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    LogUtils.i(response);
                    net.sf.json.JSONArray array = net.sf.json.JSONArray.fromObject(response);
                    boolean isfocus = false;
                    if (array != null) {
                        for (int i = 0; i < array.size(); i++) {
                            int userId = array.getInt(i);
                            if (userId == talksBean.getObj().getPostAuthor()) {
                                isfocus = true;
                            }
                        }
                    }


                    ZoneRedactPopupWindow zoneRedactPopupWindow = new ZoneRedactPopupWindow(getActivity(),
                            talksBean, new ZoneRedactPopupWindow.OnDeleteClickListener() {
                        @Override
                        public void onDeleteSuccess() {
                            items.remove(position);
                            adapter.notifyItemRemoved(position);
                        }
                    });
//                    zoneRedactPopupWindow.showPopupWindow();
                    zoneRedactPopupWindow.setIsFocus(isfocus);
                    zoneRedactPopupWindow.showPopupWindow(v);


                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(getActivity(), R.string.common_text_http_request_fail_abnormal);
                }

            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                ToastUtil.showToast(getActivity(), R.string.common_text_http_request_fail_abnormal);
            }
        });

    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void startRecordVideo(StartRecordVideoEvent event) {
//        Intent intent = new Intent(getActivity(), RecorderActivity.class);
//        startActivityForResult(intent, AddZonePopWindow.REQUEST_CODE_SELECT_VIDEO);
//        getActivity().overridePendingTransition(R.anim.push_bottom_in, R.anim.push_top_out);
//    }

    /**
     * 每次进入页面时刷新user数据
     */
    private void refreshUser() {
        User user = WeChatDBManager.getInstance().getOneUserById(userId);
        TalksBean headerBean = items.get(0);
        //昵称
        headerBean.getObj().setDevice(user.getNickName());
        //头像
        headerBean.getObj().setPostCreatetime(user.getAvatar());
        adapter.notifyItemChanged(0);
    }

    /**
     * 请求动态数据
     * http://espace.solarsource.cn:9692/espace/events/friends?password=qwert&time=1525770902178&userid=658
     *
     * @param lastTime 传当前时间则表示刷新或第一次加载，传lastTime则表示加载更多
     */
    private void getTalksData(String lastTime) {
        HashMap<String, String> params = new HashMap<>();
        if (isSelf) {
            //password
            params.put("password", EnvironmentVariable.getProperty(Constants.CHAT_PASSWORD));
        }
        params.put("time", lastTime);
        //自己的userId
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        params.put("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));

        ZoneRequestUtil.getCommonRequest(TAG, isSelf ? "events/" + dataOrigin : "shortposts/" + userId + "/u", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                //更新EV，刷新角标
                EnvironmentVariable.setProperty("zone_has_new_post", "false");
                EventBus.getDefault().post(new SystemInitOverEvent());

                try {
                    JSONArray jsonArray = new JSONArray(response);

                    if (isRefresh) {
                        refreshLayout.finishRefresh(100);
                        //清空数据，只保留第一条头部数据
                        //请求到数据，则清空原数据，没有数据则不清空数据
//                        if (jsonArray.length() > 0) {
                        if (items.size() > 1) {
                            TalksBean talksBean = items.get(0);
                            items.clear();
                            items.add(talksBean);
                        }
                        if (isSelf) {
                            // 根据EV，增加项目
                            String hasNewMessage = EnvironmentVariable.getProperty("zone_has_new_message");
                            if ("true".equals(hasNewMessage) || "false".equals(hasNewMessage)) {
                                hasNewMessage = "0";
                                EnvironmentVariable.setProperty("zone_has_new_message", "0");
                            }
                            if (hasNewMessage != null && !hasNewMessage.equals("") && !hasNewMessage.equals("0")) {
                                int count = Integer.valueOf(hasNewMessage);
                                TalksBean talksBean = new TalksBean();
                                talksBean.setObjType(0);
                                TalksBean.ObjBean objBean = new TalksBean.ObjBean();
                                objBean.setLikeCount(count);
                                talksBean.setObj(objBean);
                                items.add(talksBean);
                            }
                        }

                    } else {
                        if (jsonArray.length() == 0) {
                            ToastUtils.showShort(R.string.zone_no_more_animal);
                        }
                        refreshLayout.finishLoadMore(100);
                    }

                    for (int i = 0; i < jsonArray.length(); i++) {
                        Gson gson = new GsonBuilder().serializeNulls().create();
                        TalksBean talksBean = gson.fromJson(jsonArray.getString(i), TalksBean.class);
                        //相册类型数据，过滤掉
                        if (talksBean.getObjType() != 5) {
                            if (talksBean.getObj() == null) {
                                continue;
                            }
                            //todo 浏览次数修改
                            int count = talksBean.getObj().getReadCount()
                                    * ThumbsCommentsTransmitView.MULTI + new Random().nextInt(99);
                            talksBean.getObj().setReadCount(count);
                            items.add(talksBean);
                            //最后一条状态的时间，用于请求更多
                            lastTalksTime = talksBean.getObj().getPostCreatetime();
                        }
                    }
                    addEmptyLayoutData();
                    adapter.notifyDataSetChanged();
                    if (isRefresh) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                recyclerView.scrollToPosition(0);
                            }
                        }, 1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (isRefresh) {
                        refreshLayout.finishRefresh(100);
                    } else {
                        refreshLayout.finishLoadMore(100);
                    }
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                if (isRefresh) {
                    TalksBean talksBean = items.get(0);
                    items.clear();
                    items.add(talksBean);
                    addEmptyLayoutData();
                    adapter.notifyDataSetChanged();
                    refreshLayout.finishRefresh(100);
                } else {
                    refreshLayout.finishLoadMore(100);
                }
            }
        });
    }

    /**
     * 请求背景图
     * http://espace.solarsource.cn:9692/espace/users/u/658
     */
    private void getBackgroundImage() {

        ZoneRequestUtil.getSimpleRequest(TAG, "users/u/" + userId, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String imgUrl = jsonObject.optString("userAvatar");
                    //原来已有头部数据，更新
                    items.get(0).getObj().setPostContent(imgUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                adapter.notifyDataSetChanged();
                getTalksData(String.valueOf(System.currentTimeMillis()));
            }

            @Override
            public void onFail(String error) {
                getTalksData(String.valueOf(System.currentTimeMillis()));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNewMessageBadge(SystemInitOverEvent event) {
        String hasNewMessage = EnvironmentVariable.getProperty("zone_has_new_message");
        if (hasNewMessage != null && !hasNewMessage.equals("") && !hasNewMessage.equals("0")) {
            if ("true".equals(hasNewMessage) || "false".equals(hasNewMessage)) {
                hasNewMessage = "0";
                EnvironmentVariable.setProperty("zone_has_new_message", "0");
            }
            if (isSelf) {
                int count = Integer.valueOf(hasNewMessage);
                TalksBean talksBean = new TalksBean();
                //修改talkBean类作为消息提示类标志
                talksBean.setObjType(0);
                TalksBean.ObjBean objBean = new TalksBean.ObjBean();
                objBean.setLikeCount(count);//消息数量
                talksBean.setObj(objBean);
                if (items.size() > 1 && items.get(1) != null) {
                    if (items.get(1).getObjType() == 0) {
                        //存在消息提示,只更新
                        items.get(1).getObj().setLikeCount(count);
                        adapter.notifyItemChanged(1);
                    } else {
                        //插入
                        items.add(1, talksBean);
                        adapter.notifyItemInserted(1);
                    }
                } else {
                    items.add(talksBean);
                    adapter.notifyItemInserted(1);
                }
            }
        }

    }

    //TODO 处理tabmenu 点击(滚动到顶部)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onSolveEvent(TabMenuClickEvent event) {
        if (getArguments() != null) {
            StubObject stubObject = (StubObject) getArguments().getSerializable("stubObject");
            if (event.isChildPage(stubObject) && !isHidden()) {
                recyclerView.smoothScrollToPosition(0);
                refreshLayout.autoRefresh();
            }
        }
    }

    /**
     * 处理点赞取消点赞刷新界面
     * 及评论发送删除刷新界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLikesEvent(MobileZoneEvent mobileZoneEvent) {
        int position = mobileZoneEvent.getPosition();
        adapter.notifyItemChanged(position);
    }

    /**
     * 处理拉黑后过滤本地数据
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFilterData(MobileZoneFilterEvent event) {
        int userId = event.getUserId();
        int type = event.getType();
        if (type != 1 && dataOrigin.equals("getEventListFilterBlackList")) {
            //不是黑名单，当前是全部数据，无需刷新
            return;
        }
        if (!isSelf) {
            return;
        }

        if (items != null) {
            Iterator<TalksBean> iterator = items.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().getObj().getPostAuthor() == userId) {
                    iterator.remove();
                }
            }
            addEmptyLayoutData();
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 发说说
     *
     * @param talksBean 说说消息体
     */
    private void sendPost(final TalksBean talksBean) {
        LogUtils.d("sendPost---------------------->>");
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        params.put("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));
        params.put("device", talksBean.getObj().getDevice());
        params.put("content", talksBean.getObj().getPostContent());
        ZoneRequestUtil.postCommonRequest(TAG, "shortposts", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {

                    JSONObject jsonObject = new JSONObject(response);
                    if ("101000".equals(jsonObject.optString("status"))) {
                        int shortPostId = jsonObject.optInt("shortpostid");

                        int integral = 0;
                        try {
                            JSONObject postObject = jsonObject.optJSONObject("shortpost");
                            integral = postObject.optInt("integral");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        StatusAlert.successAlert(getActivity(), LayoutInflater.from(getActivity())
                                .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_publish_success));
                        TalksBean.ObjBean objBean = talksBean.getObj();
                        objBean.setIntegral(integral);
                        objBean.setId(shortPostId);
                        talksBean.setObj(objBean);
                        if (items.get(1) != null && items.get(1).getObjType() == 0) {
                            //有消息提示
                            items.add(2, talksBean);
                            adapter.notifyItemInserted(2);
                            recyclerView.scrollToPosition(2);
                        } else {
                            items.add(1, talksBean);
                            adapter.notifyItemInserted(1);
                            recyclerView.scrollToPosition(1);
                        }

                    } else {
                        StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                                .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_publish_fail));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                            .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_publish_fail));
                }


            }

            @Override
            public void onFail(String error) {
                StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_publish_fail));
            }
        });
    }

//    /**
//     * 处理说说发送
//     *
//     * @param mobileZoneSendContentEvent
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onCommentEvent(MobileZoneSendContentEvent mobileZoneSendContentEvent) {
//        sendPost(mobileZoneSendContentEvent.getTalksBean());
//    }

    /**
     * 处理说说转发
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCommentEvent(MobileZoneTransmitContentEvent mobileZoneSendContentEvent) {
        transmitPost(mobileZoneSendContentEvent.getTalksBean());
    }

    /**
     * 处理详情页有数据变化时，返回主页面刷新item
     *
     * @param mobileZoneDetailBackEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDetailBackEvent(MobileZoneDetailBackEvent mobileZoneDetailBackEvent) {
        int position = mobileZoneDetailBackEvent.getPosition();
        TalksBean talksBean = mobileZoneDetailBackEvent.getTalksBean();
        items.remove(position);
        items.add(position, talksBean);
        adapter.notifyItemChanged(position);
    }

    /**
     * 转发说说
     *
     * @param talksBean 消息体
     */
    private void transmitPost(final TalksBean talksBean) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        params.put("password", EnvironmentVariable.getProperty(CHAT_PASSWORD));
        params.put("device", talksBean.getObj().getDevice());
        params.put("transmit_status", "" + talksBean.getObj().getTransmitStatus());
        params.put("transmit_content", "" + talksBean.getObj().getTransmitContent());
        params.put("content", "" + talksBean.getObj().getTransmitSourceId());
        LoadingDataUtilBlack.show(ActivityUtils.getTopActivity(),ResStringUtil.getString(R.string.common_text_please_wait));
        ZoneRequestUtil.postCommonRequest(TAG, "shortposts", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {

                    JSONObject jsonObject = new JSONObject(response);
                    if ("101000".equals(jsonObject.optString("status"))) {
                        int shortPostId = jsonObject.optInt("shortpostid");
                        StatusAlert.successAlert(getActivity(), LayoutInflater.from(getActivity())
                                .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_forward_success));
                        TalksBean.ObjBean objBean = talksBean.getObj();
                        int integral = 0;
                        try {
                            JSONObject postObject = jsonObject.optJSONObject("shortpost");
                            integral = postObject.optInt("integral");
                            objBean.setIntegral(integral);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        objBean.setId(shortPostId);
                        talksBean.setObj(objBean);
                        if (isSelf) {
                            if (items.get(1) != null && items.get(1).getObjType() == 0) {
                                //有消息提示
                                items.add(2, talksBean);
                                adapter.notifyItemInserted(2);
                                recyclerView.scrollToPosition(2);
                            } else {
                                items.add(1, talksBean);
                                adapter.notifyItemInserted(1);
                                recyclerView.scrollToPosition(1);
                            }
                        }
                        EventBus.getDefault().post(new MobileZoneRefreshEvent(talksBean, "transmit"));
                    } else {
                        StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                                .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_forward_fail));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                            .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_forward_fail));
                }

            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_forward_fail));
            }
        });
    }

    /**
     * 更改主页背景图
     */
    private void changeBgImage() {
        new AlertDialog.Builder(getContext()).setMessage(R.string.zone_update_background_photo)
                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(getContext(), JFPicturePickPhotoWallActivity.class);
                        intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, 1);//可选择的最大照片数
                        intent.putExtra("sendBtnName", getResources().getString(R.string.common_text_confirm));
                        intent.putExtra(JFPicturePickPhotoWallActivity.SHOW_RAW_PIC, false);
                        startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
                    }
                }).setNegativeButton(R.string.common_text_cancel, null).show();
    }

    /**
     * post 请求更改图片背景
     *
     * @param url 图片的url地址
     */
    private void postBgImage(final String url) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userid", EnvironmentVariable.getProperty(CHAT_USER_ID));
        params.put("topic", url);
        ZoneRequestUtil.postCommonRequest(TAG, "users/u", params, new ZoneRequestUtil.ZoneRequestCallback() {
            @Override
            public void onSuccess(String response) {
                items.get(0).getObj().setPostContent(url);
                adapter.notifyItemChanged(0);
                LoadingDataUtilBlack.dismiss();
                StatusAlert.successAlert(getActivity(), LayoutInflater.from(getActivity())
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_update_background_success));
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                StatusAlert.failAlert(getActivity(), LayoutInflater.from(getActivity())
                        .inflate(R.layout.mobile_zone_activity_main_zone, null), ResStringUtil.getString(R.string.zone_update_background_fail));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1, sticky = true)
    public void onRefresh(ShareToZoneRefreshEvent event) {
        ShareToZoneRefreshEvent stickyEvent = EventBus.getDefault().removeStickyEvent(ShareToZoneRefreshEvent.class);
        // Better check that an event was actually posted before
        if (stickyEvent != null) {
            // Now do something with it
            refreshLayout.autoRefresh();
        }
    }

    /**
     * 处理请求用户信息后刷新界面
     *
     * @param userEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerUserEvent(UserEvent userEvent) {
        if (adapter != null && userEvent.getEventType() == UserEvent.EVENT_ZONE) {
            //是空间请求的user 才会刷新
            addEmptyLayoutData();
            adapter.notifyDataSetChanged();

            //用户id 跟传进来的一样
            if (tvTitle != null && userEvent.getUser().getId() == userId) {
                tvTitle.setText(userEvent.getUser().getNickName() + ResStringUtil.getString(R.string.zone_s_gravitational));
            }
        }
    }

    /**
     * 添加空白布局的数据
     */
    private void addEmptyLayoutData(){
        if(items.size() == 1){
            TalksBean emptyBean = new TalksBean();
            emptyBean.setObjType(-1);
            items.add(emptyBean);
        }
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).init();
    }
}
